<template>
  <ContentWrap>
    <div class="mx-auto">
      <!-- 头部导航栏 -->
      <div
        class="absolute top-0 left-0 right-0 h-50px bg-white border-bottom z-10 flex items-center px-20px"
      >
        <!-- 左侧标题 -->
        <div class="w-200px flex items-center overflow-hidden">
          <Icon icon="ep:arrow-left" class="cursor-pointer flex-shrink-0" @click="handleBack()" />
          <span class="ml-10px text-16px truncate">
            {{ formData.id ? '编辑知识库文档' : '创建知识库文档' }}
          </span>
        </div>

        <!-- 步骤条 -->
        <div class="flex-1 flex items-center justify-center h-full">
          <div class="w-400px flex items-center justify-between h-full">
            <div
              v-for="(step, index) in steps"
              :key="index"
              class="flex items-center mx-15px relative h-full"
              :class="[
                currentStep === index
                  ? 'text-[#3473ff] border-[#3473ff] border-b-2 border-b-solid'
                  : 'text-gray-500'
              ]"
            >
              <div
                class="w-28px h-28px rounded-full flex items-center justify-center mr-8px border-2 border-solid text-15px"
                :class="[
                  currentStep === index
                    ? 'bg-[#3473ff] text-white border-[#3473ff]'
                    : 'border-gray-300 bg-white text-gray-500'
                ]"
              >
                {{ index + 1 }}
              </div>
              <span class="text-16px font-bold whitespace-nowrap">{{ step.title }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 主体内容 -->
      <div class="mt-50px">
        <!-- 第一步：上传文档 -->
        <div v-if="currentStep === 0" class="mx-auto w-560px">
          <UploadStep v-model="formData" ref="uploadDocumentRef" />
        </div>

        <!-- 第二步：文档分段 -->
        <div v-if="currentStep === 1" class="mx-auto w-560px">
          <SplitStep v-model="formData" ref="documentSegmentRef" />
        </div>

        <!-- 第三步：处理并完成 -->
        <div v-if="currentStep === 2" class="mx-auto w-560px">
          <ProcessStep v-model="formData" ref="processCompleteRef" />
        </div>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { KnowledgeDocumentApi } from '@/api/ai/knowledge/document'
import { useRoute, useRouter } from 'vue-router'
import UploadStep from './UploadStep.vue'
import SplitStep from './SplitStep.vue'
import ProcessStep from './ProcessStep.vue'
import { useTagsView } from '@/hooks/web/useTagsView'

defineOptions({ name: 'AiKnowledgeDocumentForm' })

const route = useRoute() // 路由
const router = useRouter() // 路由
const tagsView = useTagsView()

const uploadDocumentRef = ref()
const documentSegmentRef = ref()
const processCompleteRef = ref()
const currentStep = ref(0)
const steps = [{ title: '上传文档' }, { title: '文档分段' }, { title: '处理完成' }]
const formData = ref({
  knowledgeId: undefined, // 知识库编号
  id: undefined,
  segmentMaxTokens: 500,
  list: [] as Array<{
    id: number
    name: string
    url: string
    segments: Array<{
      content?: string
      contentLength?: number
      tokens?: number
    }>
    segmentMaxTokens?: number // 当前segments使用多大的maxTokens切分的，用于segments缓存
    count?: number    // 段落数量
    process?: number  // 处理进度
  }>
})

// 提供parent给到子组件
provide('parent', getCurrentInstance())

const initData = async () => {
  if (route.query.knowledgeId) {
    formData.value.knowledgeId = route.query.knowledgeId as any
  }

  // 修改场景
  const documentId = route.query.id as any
  if (documentId) {
    formData.value.id = documentId
    const document = await KnowledgeDocumentApi.getKnowledgeDocument(documentId)
    formData.value.segmentMaxTokens = document.segmentMaxTokens
    formData.value.list = [
      {
        id: document.id,
        name: document.name,
        url: document.url,
        segments: []
      }
    ]
    currentStep.value = 1
  }
}

const gotoPrevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const gotoNextStep = () => {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++
  }
}

const handleBack = (reload: boolean = false) => {
  tagsView.closeCurrent()
  router.push({ name: 'AiKnowledgeDocument', query: { knowledgeId: formData.value.knowledgeId }, state: { reload } })
}

/** 暴露给子组件调用 */
defineExpose({
  gotoPrevStep,
  gotoNextStep,
  handleBack,
})

onMounted(async () => {
  await initData()
})

onBeforeUnmount(() => {
  uploadDocumentRef.value = null
  documentSegmentRef.value = null
  processCompleteRef.value = null
})
</script>

<style scoped lang="scss">
.border-bottom {
  border-bottom: 1px solid #dcdfe6;
}

.text-primary {
  color: #3473ff;
}

.bg-primary {
  background-color: #3473ff;
}

.border-primary {
  border-color: #3473ff;
}
</style>
